# upload.py
import zipfile

from fastapi import APIRouter, UploadFile, Form, File
from fastapi.responses import JSONResponse
from pathlib import Path
import shutil
from pathlib import Path as SysPath

router = APIRouter()

@router.post("/upload/")
async def upload_images(concept: str = Form(...), files: list[UploadFile] = File(...)):
    save_dir = SysPath("./uploads") / concept
    save_dir.mkdir(parents=True, exist_ok=True)

    for file in files:
        file_path = save_dir / file.filename
        with file_path.open("wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

    return {"message": f"{len(files)} 张图片已上传至 {save_dir}"}


@router.post("/upload_zip/")
async def upload_zip(concept: str = Form(...), file: UploadFile = File(...)):
    save_dir = SysPath("./uploads") / concept
    save_dir.mkdir(parents=True, exist_ok=True)

    zip_path = save_dir / "upload.zip"
    with open(zip_path, "wb") as f:
        shutil.copyfileobj(file.file, f)

    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.extractall(save_dir)

    zip_path.unlink()  # 删除 zip 文件
    return {"message": f"已解压上传内容至 {save_dir}"}
